package com.lej.upgrade

import android.Manifest
import android.app.Activity
import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import androidx.annotation.RequiresApi
import androidx.core.app.ActivityCompat
import androidx.core.content.FileProvider
import com.lej.core.utils.extention.toast
import com.lej.upgrade.AndroidOPermissionActivity.Companion.INSTALL_TYPE
import java.io.File

/**
 * 兼容Android 8。0 APP 在线更新，权限申请界面
 */
class AndroidOPermissionActivity : Activity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
            finish()
            return
        }
        ActivityCompat.requestPermissions(
            this,
            arrayOf(Manifest.permission.REQUEST_INSTALL_PACKAGES),
            INSTALL_PACKAGES_REQUESTCODE
        )
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    override fun onRequestPermissionsResult(
        code: Int,
        permissions: Array<String>,
        results: IntArray
    ) {
        super.onRequestPermissionsResult(code, permissions, results)
        if (code == INSTALL_PACKAGES_REQUESTCODE) {
            if (results.getOrNull(0) == PackageManager.PERMISSION_GRANTED) {
                sListener?.invoke(true)
                finish()
            } else {
                showDialog()
            }
        }
    }

    private fun showDialog() {
        AlertDialog.Builder(this)
            .setTitle(R.string.app_name)
            .setCancelable(false)
            .setMessage(DescRequestInstall)
            .setPositiveButton("设置") { dialog, _ ->
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    startInstallPermissionSettingActivity()
                }
                dialog?.dismiss()
            }
            .setNegativeButton("取消") { dialog, _ ->
                sListener?.invoke(false)
                dialog?.dismiss()
                finish()
            }.create().show()
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private fun startInstallPermissionSettingActivity() { //注意这个是8.0新API
        val intent = Intent(
            Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES,
            Uri.parse("package:$packageName")
        )
        startActivityForResult(intent, START_INSTALL_PERMISSION_SETTING)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        sListener?.invoke(requestCode == START_INSTALL_PERMISSION_SETTING && resultCode == RESULT_OK)
        finish()
    }

    override fun onDestroy() {
        super.onDestroy()
        sListener = null
    }

    companion object {
        const val INSTALL_PACKAGES_REQUESTCODE = 1
        const val START_INSTALL_PERMISSION_SETTING = 2342
        var sListener: ((Boolean) -> Unit)? = null
        const val INSTALL_TYPE = "application/vnd.android.package-archive"
        const val DescRequestInstall = "为了正常升级本APP，请点击设置按钮，允许安装未知来源应用\n此功能只会用于本APP版本升级"
    }
}

fun Context.checkPermissionAndInstall(versionCode: String?) {
    versionCode?:return
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O
        || packageManager.canRequestPackageInstalls()
    ) {
        return install(versionCode)
    }
    AndroidOPermissionActivity.sListener = {
        if (it) install(versionCode) else "授权失败，无法安装应用".toast()
    }
    startActivity(Intent(this, AndroidOPermissionActivity::class.java))
}

private fun Context.install(versionCode: String) {
    val uri: Uri = FileProvider.getUriForFile(
        this,
        "$packageName.downloadProvider",
        File(cacheDir, "${versionCode}.apk")
    )
    startActivity(Intent().apply {
        addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        action = Intent.ACTION_VIEW
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
        }
        setDataAndType(uri, INSTALL_TYPE)
    })
}

fun Long.getPrintByteSize(): String {
    var size = this
    if (size < 1024) return "${size}B"
    size = size ushr 10
    if (size < 1024) return "${size}KB"
    size = size ushr 10
    if (size < 1024) return (size * 100L).let { "${it / 100}.${it % 100}MB" }
    size = size ushr 10
    return (size * 100L).let { "${it / 100}.${it % 100}GB" }
}